using BackData;
using Domain.DTOs.RBAC;
using Domain.RBAC;
using Infratructure;
using MediatR;
using SqlSugar;
using Team.API.Applocation.Command.Users.Permissions;

namespace Team.API.Applocation.Handler.Users.Permissions
{
    /// <summary>
    /// 查询权限树形结构处理器
    /// </summary>
    public class QueryPermissionTreeHandler : IRequestHandler<QueryPermissionTreeCommand, APIResult<List<PermissionDTO>>>
    {
        private readonly IRepository<Permissionmodel> permissionRepository;

        public QueryPermissionTreeHandler(IRepository<Permissionmodel> permissionRepository)
        {
            this.permissionRepository = permissionRepository;
        }

        public async Task<APIResult<List<PermissionDTO>>> Handle(QueryPermissionTreeCommand request, CancellationToken cancellationToken)
        {
            // 查询所有权限
            var allPermissions = await permissionRepository.GetAll()
                .Where(p => p.IsDel == false)
                .WhereIF(request.OnlyEnabled, p => p.Status == 1)
                .WhereIF(request.PermissionType.HasValue, p => p.PermissionType == request.PermissionType!.Value)
                .OrderBy(p => p.Sort)
                .OrderBy(p => p.Id)
                .Select(p => new PermissionDTO
                {
                    Id = p.Id,
                    PermissionCode = p.PermissionCode,
                    PermissionName = p.PermissionName,
                    PermissionUrl = p.PermissionUrl,
                    ParentId = p.ParentId,
                    PermissionType = p.PermissionType,
                    Icon = p.Icon,
                    Sort = p.Sort,
                    Status = p.Status,
                    Description = p.Description,
                    Remark = p.Remark
                })
                .ToListAsync();

            // 构建树形结构
            var tree = BuildTree(allPermissions, 0);

            return APIResult<List<PermissionDTO>>.Ok("获取权限树成功", tree);
        }

        /// <summary>
        /// 递归构建权限树
        /// </summary>
        private List<PermissionDTO> BuildTree(List<PermissionDTO> allPermissions, long parentId)
        {
            var children = allPermissions
                .Where(p => p.ParentId == parentId)
                .OrderBy(p => p.Sort)
                .ThenBy(p => p.Id)
                .ToList();

            foreach (var child in children)
            {
                child.Children = BuildTree(allPermissions, child.Id);
            }

            return children;
        }
    }
}

